package com.example.framework.web.core.filter;

import com.example.framework.common.util.servlet.ServletUtils;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

public class CacheRequestBodyWrapper extends HttpServletRequestWrapper {

    private final byte[] requestBody;

    public CacheRequestBodyWrapper(HttpServletRequest request) {
        super(request);
        // 获取消息中body
        this.requestBody = ServletUtils.getBodyBytes(request);
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        // request.getReader() 和 request.getInputStream() 都是只能调用一次
        // 且 getReader() 方法底层也是调用 getInputStream() 来实现的.
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public int available() {
                return requestBody.length;
            }
        };
    }
}